﻿using Furion.FriendlyException;
using Radius.NET.Application.Const;
using Radius.NET.Application.Entity;
using Radius.NET.Application.Util;
using Radius.NET.Core.Service;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Radius.NET.Application
{
    /// <summary>
    /// 业务单据编码服务
    /// </summary>
    [ApiDescriptionSettings(ApplicationConst.GroupName, Order = 001)]
    public class AppSerialNumberService: BaseService<AppSerialNumber>,ITransient
    {
        private SqlSugarRepository<AppSerialNumber> _appSerialNumberRep;

        public AppSerialNumberService(SqlSugarRepository<AppSerialNumber> appSerialNumberRep)
            :base(appSerialNumberRep)
        {
            _appSerialNumberRep = appSerialNumberRep;
        }

        #region 生成编码
        /// <summary>
        /// 生成编码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<string> GenerateNumber(string code)
        {
            var serial = await _appSerialNumberRep.GetFirstAsync(x => x.Code == code);
            if (serial == null)
            {
                throw Oops.Bah("此编码规则不存在！");
            }
            DocumentNumberGenerator generator = new DocumentNumberGenerator(serial);
            return generator.GenerateNextNumber(async (res) =>
            {
                await _appSerialNumberRep.Context.Updateable(res).ExecuteCommandAsync();
            });
        } 
        #endregion

    }
}
